# background ratio calculation
# 2011/02/05 

file <- commandArgs(trailingOnly =T)[1]
outFile <- commandArgs(trailingOnly =T)[2]
windowPlotFile <- commandArgs(trailingOnly =T)[3]
data <- read.table(file, header=T, sep="\t");
attach(data)


C_sorted <- sort(Control, decreasing=TRUE)
C <- C_sorted[as.integer(length(Control) * 0.01)]

S_sorted <- sort(Sample, decreasing=TRUE)
S <- S_sorted[as.integer(length(Sample) * 0.01)]

newS <- Sample[Control > C & Sample < S]
newC <- Control[Control > C & Sample < S]
fit <- lm(newS ~ newC - 1)
fit.co <- fit$coefficients
names(fit.co) <- NULL
ratio <- fit.co[1]

jpeg(file=windowPlotFile, width=400, height=400)
plot(Control, Sample, col = ifelse(Control > C & Sample < S, "green", "black"), pch=20, cex = .8)
abline(0, ratio, col="red")
legend("topright", lty=1, lwd=1, col="red", legend=paste("background ratio = ", sprintf("%.3f", ratio), sep=""))
graphics.off()

cat(ratio, file=outFile)


